package com.ray.business.service.compose;

import com.ray.business.builder.BusinessVOBuilder;
import com.ray.business.enums.SaleStatusEnum;
import com.ray.business.service.ProdPurchaseBackService;
import com.ray.business.service.ProdPurchaseService;
import com.ray.business.table.entity.ProdBusiness;
import com.ray.business.table.entity.ProdBusinessDeduction;
import com.ray.business.table.entity.ProdPurchase;
import com.ray.business.table.entity.ProdPurchaseBack;
import com.ray.business.table.vo.BusinessVO;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 采购服务
 * @Class: PurcahseService
 * @Package com.ray.business.service.compose
 * @date 2020/6/21 17:10
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
public class PurcahseService {

    @Autowired
    private ProdPurchaseService prodPurchaseService;
    @Autowired
    private ProdPurchaseBackService prodPurchaseBackService;


    public List<BusinessVO> queryPurchaseByBIllNo(String billNo, String customerName, LoginUser loginUser) {
        Assert.hasLength(billNo,"参数[billNo]不能为空");
        //获取对账单对应的扣款单
        List<ProdPurchaseBack> prodPurchaseBacks = prodPurchaseBackService.listByBillNo(billNo, SaleStatusEnum.FINISH.getValue(),loginUser);
        final Map<String, BigDecimal> decimalMap = prodPurchaseBacks.stream()
                .collect(Collectors.groupingBy(ProdPurchaseBack::getOrderNo,Collectors.reducing(BigDecimal.ZERO,ProdPurchaseBack::getTotalAmount,BigDecimal::add)));

        List<ProdPurchase> prodBusinesses = prodPurchaseService.queryPurchaseByBIllNo(billNo,loginUser);
        //转换
        return  prodBusinesses.stream().map(prodPurchase -> {
            return new BusinessVOBuilder().append(prodPurchase).appendCustomerName(customerName).appendDeductionAmount(decimalMap.get(prodPurchase.getOrderNo())).bulid();
        }).collect(Collectors.toList());
    }
}
